#include <sys/socket.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>


int main(int argc, char const *argv[])
{
    // 1.创建套接字

    int sockfd= socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
        perror("socket error");
        exit(EXIT_FAILURE);
    }
    printf("sockfd = %d\n", sockfd);
    struct sockaddr_in sever_addr;
   
    bzero(&sever_addr, sizeof(sever_addr));
    sever_addr.sin_family = AF_INET; // 地址簇
    sever_addr.sin_port = htons(atoi(argv[2]));
    sever_addr.sin_addr.s_addr = inet_addr(argv[1]);
    // 2. 建立连接
    int ret = connect(sockfd, (const struct sockaddr *) &sever_addr, sizeof(sever_addr));
    if (ret == -1) {
        perror("connect");
        exit(EXIT_FAILURE);
    }
    char sbuff[1024] = {0};
    strcpy(sbuff, "hello world");
    // 3.先测试发送数据
    ssize_t sbytes = send(sockfd, sbuff, strlen(sbuff), 0);
    if (sbytes == -1) {
        perror("send error");
        exit(EXIT_FAILURE);
    }
    // 4. 测试接受数据
    char rbuff[1024] = {0};

    ssize_t rbytes = recv(sockfd, rbuff, sizeof(rbuff), 0);

    if (rbytes == -1) {
        perror("recv error");
        exit(EXIT_FAILURE);
    } else if (rbytes == 0) {
        printf("server is offline\n");
    } else {
        printf("recv data:%s\n", rbuff);
    }

    close(sockfd);
    return 0;
}
